package com.lintf.jwt.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lintf.jwt.dao.UserMapper;
import com.lintf.jwt.entity.User;
import com.lintf.jwt.entity.UserPermissions;
import com.lintf.jwt.service.UserPermissionsService;
import com.lintf.jwt.service.UserService;
import com.lintf.jwt.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/3/15-16:44
 * @ package_name:com.lintf.jwt.service.impl
 * @ project_name:SpringSecurity-JWT
 * @ desc:用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private UserPermissionsService userPermissionsService;

    @Override
    public User register(User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(!StringUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername());
        if (this.list(qw).size() > 0) {
            return null;
        }
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return user;
    }

    @Override
    public String login(String username, String password) {
        String token = "";
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    //    第一版
//    @Override
//    public List<UserPermissions> getPermissionList(Long userId) {
//        QueryWrapper<UserPermissions> qwp = new QueryWrapper<>();
//        qwp.lambda().eq(!StringUtils.isEmpty(userId), UserPermissions::getId, userId);
//        List<UserPermissions> permissionList = userPermissionsService.list();
//        return permissionList;
//    }
    @Override
    public List<UserPermissions> getPermissionList(String username) {
//    QueryWrapper<UserPermissions> qwp = new QueryWrapper<>();
//    qwp.lambda().eq(!StringUtils.isEmpty(userId), UserPermissions::getId, userId);
        List<UserPermissions> permissionList = userPermissionsService.selectUserPermissions(username);
        return permissionList;
    }

    @Override
    public List<User> getlist(User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda()
                .like(!StringUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername())
                .eq(!StringUtils.isEmpty(user.getPassword()), User::getPassword, user.getPassword())
                .like(!StringUtils.isEmpty(user.getNickName()), User::getNickName, user.getNickName())
                .eq(!StringUtils.isEmpty(user.getStatus()), User::getStatus, user.getStatus());

        return this.list(qw);
    }

//    @Override
//    public User getOne(QueryWrapper queryWrapper) {
//        QueryWrapper qw = new QueryWrapper(queryWrapper);
//        User user = userMapper.selectOne(queryWrapper);
//        return user;
//    }
}


